package com.ufo.store.management.ui.activity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jaredrummler.materialspinner.MaterialSpinner;
import com.nineoldandroids.view.ViewHelper;
import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.adapter.SaleDetailRecyclerViewAdapter;
import com.ufo.store.management.database.DatabaseManager;
import com.ufo.store.management.entity.PayMaster;
import com.ufo.store.management.entity.SaleDetailInfo;
import com.ufo.store.management.utils.ScreenUtil;
import com.ufo.store.management.utils.StatusBarUtil;
import com.ufo.store.management.utils.Utils;
import com.ufo.store.management.widget.layout.TouchFrameLayout;
import com.ufo.store.management.widget.recyclerview.EndlessRecyclerOnScrollListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2015/11/3 0003.
 */
public class SearchSaleDetailActivity extends BaseActivity implements Handler.Callback {
    private String TAG = SearchSaleDetailActivity.class.getSimpleName();
    private final int SEARCH_BY_SALEDETAIL_BILLNO = 1;
    private static final int LOAD_DATA_FINISH = 10;
    private static final int REFRESH_DATA_FINISH = 11;

    private ImageView mReturnIv = null;
    private RelativeLayout mSearchControlRl = null;
    private EditText mSearchEt = null;
    private RelativeLayout mSearchResultRl = null;
    private RelativeLayout mProcessTipLy = null;
    private LinearLayout mGetSaleDetailFailTipLy = null;
    private TextView mSaleDetailFailTipTv = null;

    private MaterialSpinner spinner = null;
//    private RelativeLayout mSearchModeRl = null;
//    private TextView mSearchResultTv = null;
//private TextView mModeSelectTv = null;

    private RecyclerView mSaleDetailRecyclerView = null;
    private SaleDetailRecyclerViewAdapter mSaleDetailRecyclerViewAdapter = null;
    private SwipeRefreshLayout mSwipeRefreshLayout = null;

    private View mActivityRootView = null;
    private TouchFrameLayout mSearchMaskV = null;
    private ImageView mDeleteIv = null;

    private Handler mHandler = null;

    private String mSearchStr = null;
    private int mReadIndex = 0;
    private boolean mIsSearchControlRlHided = false;
    private int mSearchMode = SEARCH_BY_SALEDETAIL_BILLNO;

    private int mMoveStartY = 0;
    private int mMoveDurY = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        StatusBarUtil.StatusBarLightMode(this, R.color.app_bar_color, true);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case REFRESH_DATA_FINISH:
                if (mSaleDetailRecyclerViewAdapter != null) {
                    List<PayMaster> data = (List<PayMaster>) msg.obj;
                    mSaleDetailRecyclerViewAdapter.setData(data);
                    mSaleDetailRecyclerViewAdapter.notifyDataSetChanged();
                    showResultView();
                }
                break;
            case LOAD_DATA_FINISH:
                if (mSaleDetailRecyclerViewAdapter != null) {
                    List<PayMaster> data = (List<PayMaster>) msg.obj;
                    mSaleDetailRecyclerViewAdapter.insertData(data);
                    mSaleDetailRecyclerViewAdapter.notifyDataSetChanged();
                    showResultView();
                }
                break;
        }
        return false;
    }

    private void initData() {
        mHandler = new Handler(this);
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();

        }
    }

    private void initView() {
        setContentView(R.layout.activity_sale_detail_search);
        mActivityRootView = findViewById(R.id.activityRoot);
        mActivityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                mActivityRootView.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = mActivityRootView.getRootView().getHeight() - rect.bottom;
                if (rootInvisibleHeight > ScreenUtil.getScreenSize(getActivity())[1] / 3) {
                    displayWithAnimator(mSearchMaskV, 1.0f, 500);
                } else {
                    displayWithAnimator(mSearchMaskV, .0f, 500);
                }
            }
        });

        mReturnIv = (ImageView) findViewById(R.id.iv_back);
        mReturnIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager inputManager = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0); //强制隐藏键盘
                finish();
            }
        });

        mSearchControlRl = (RelativeLayout) findViewById(R.id.search_control_Rl);
        mSearchMaskV = (TouchFrameLayout) findViewById(R.id.v_search_mask);
        mSearchMaskV.setClickListener(new TouchFrameLayout.OnClick() {
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mSaleDetailRecyclerView.getWindowToken(), 0);
                displayWithAnimator(mSearchMaskV, .0f, 500);
            }
        });

        spinner = (MaterialSpinner) findViewById(R.id.spinner);
        spinner.setItems("账单号");
        spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override
            public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mSaleDetailRecyclerView.getWindowToken(), 0);
                switch (position) {
                    case 0:
                        mSearchMode = SEARCH_BY_SALEDETAIL_BILLNO;
                        GetSaleDetailInfoTask(true);
                        break;
                }
            }
        });

//        mSearchResultTv = (TextView) findViewById(R.id.search_result_tv);
//        mSearchModeRl = (RelativeLayout) findViewById(R.id.search_mode_rl);
//        mModeSelectTv = (TextView) findViewById(R.id.search_mode_tv);
//        mModeSelectTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//            }
//        });
//        mSearchModeRl.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });

        mSearchEt = (EditText) findViewById(R.id.search_et);
        mSearchEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSearchStr = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    mDeleteIv.setVisibility(View.GONE);
                } else {
                    mDeleteIv.setVisibility(View.VISIBLE);
                }
            }
        });

        mSearchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    mSearchStr = mSearchEt.getText().toString();
                    GetSaleDetailInfoTask(true);
                    return true;
                }
                return false;
            }
        });

        mDeleteIv = ((ImageView) findViewById(R.id.iv_search_delete));
        mDeleteIv.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mSearchEt.setText("");
                mSearchEt.requestFocus();
                InputMethodManager inputManager = (InputMethodManager) mSearchEt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(mSearchEt, 0);
            }
        });


        mSearchResultRl = (RelativeLayout) findViewById(R.id.search_result_Rl);
        mProcessTipLy = (RelativeLayout) findViewById(R.id.progress_tip_ly);
        mGetSaleDetailFailTipLy = (LinearLayout) findViewById(R.id.get_sale_detail_fail_tip_ly);
        mSaleDetailFailTipTv = (TextView) findViewById(R.id.get_sale_detail_list_fail_tv);

        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh_layout);
        mSwipeRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, getResources().getDisplayMetrics()));
        mSwipeRefreshLayout.setColorSchemeResources(R.color.upgrade_orange, R.color.share_green, R.color.red);
        mSwipeRefreshLayout.setProgressViewEndTarget(true, 200);  //改变下拉长度
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                GetSaleDetailInfoTask(true);
            }
        });

        mSaleDetailRecyclerView = (RecyclerView) findViewById(R.id.saledetail_recyclerview);
        mSaleDetailRecyclerView.setLayoutManager(new LinearLayoutManager(SearchSaleDetailActivity.this));
        mSaleDetailRecyclerViewAdapter = new SaleDetailRecyclerViewAdapter(SearchSaleDetailActivity.this);
        mSaleDetailRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mSaleDetailRecyclerView.setHasFixedSize(true);
        mSaleDetailRecyclerView.setAdapter(mSaleDetailRecyclerViewAdapter);
        mSaleDetailRecyclerViewAdapter.setOnClickListener(new SaleDetailRecyclerViewAdapter.OnClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                PayMaster payMaster = mSaleDetailRecyclerViewAdapter.getItem(position);
                Intent toIntent = new Intent(SearchSaleDetailActivity.this, SaleDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("Billno", payMaster.payMasterBillno);
                toIntent.putExtras(bundle);
                startActivity(toIntent);
            }

            @Override
            public void onItemLongClick(View v, int position) {

            }
        });

        mSaleDetailRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        mMoveDurY = 0;
                        mMoveStartY = 0;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mMoveStartY == 0) {
                            mMoveStartY = (int) event.getY();
                        }
                        int _TempY = (int) event.getY();
                        mMoveDurY = _TempY - mMoveStartY;   //负数向上移动，正数向下移动
                        if (mMoveDurY < -Utils.dp2px(getResources(), 80) && mIsSearchControlRlHided == false) {
                            mMoveDurY = 0;
                            mMoveStartY = 0;
                            mIsSearchControlRlHided = true;
                            menuCollapse();
                        } else if (mMoveDurY > Utils.dp2px(getResources(), 80) && mIsSearchControlRlHided == true) {
                            mMoveDurY = 0;
                            mMoveStartY = 0;
                            mIsSearchControlRlHided = false;
                            menuExpand();
                        }
                        break;
                }
                return false;
            }
        });

        mSaleDetailRecyclerView.addOnScrollListener(mOnScrollListener);

        //显示搜索栏
        mSearchControlRl.setTranslationY(0);
        mSearchResultRl.setTranslationY(getResources().getDimension(R.dimen.search_control_height));
    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {
        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            //这里没有下拉加载

        }
    };

    private android.animation.Animator mAnimatorControl;
    private android.animation.Animator mAnimatorContent;

    /**
     * @desc 动画隐藏标题栏，true 显示， false 隐藏
     * @author taoli
     * @time 2017/2/15 0015
     */
    private void showHideTitleBar(boolean tag) {
        if (mAnimatorControl != null && mAnimatorControl.isRunning()) {
            mAnimatorControl.cancel();
        }
        if (mAnimatorContent != null && mAnimatorContent.isRunning()) {
            mAnimatorContent.cancel();
        }
        if (tag) {
            mAnimatorControl = ObjectAnimator.ofFloat(mSearchControlRl, "translationY", mSearchControlRl.getTranslationY(), 0);
            mAnimatorContent = ObjectAnimator.ofFloat(mSearchResultRl, "translationY", mSearchResultRl.getTranslationY(), getResources().getDimension(R.dimen.search_control_height));
        } else {
            mAnimatorControl = ObjectAnimator.ofFloat(mSearchControlRl, "translationY", mSearchControlRl.getTranslationY(), -mSearchControlRl.getHeight());
            mAnimatorContent = ObjectAnimator.ofFloat(mSearchResultRl, "translationY", mSearchResultRl.getTranslationY(), 0);
        }
        mAnimatorControl.start();
        mAnimatorContent.start();
    }

    private void menuCollapse() {
        showHideTitleBar(false);
    }

    private void menuExpand() {
        showHideTitleBar(true);
    }

    private void GetSaleDetailInfoTask(boolean headerOrFooter) {
        if (this.isFinishing()) {
            return;
        }
        if (mSearchStr == null || mSearchStr.length() == 0) {
            mSaleDetailRecyclerView.setVisibility(View.GONE);
            mProcessTipLy.setVisibility(View.GONE);
            mGetSaleDetailFailTipLy.setVisibility(View.VISIBLE);
            mSaleDetailFailTipTv.setText("无搜索结果");
            mSwipeRefreshLayout.setRefreshing(false);
            return;
        }
        if (!BarApplication.getInstance().mDatabaseIsSqlServer) {
            return;
        }
        new GetSaleDetailInfoTask(headerOrFooter).execute();
    }

    private class GetSaleDetailInfoTask extends AsyncTask<String, Void, List<PayMaster>> {
        private boolean mHeaderOrFooter;

        public GetSaleDetailInfoTask(boolean headerOrFooter) {
            mHeaderOrFooter = headerOrFooter;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mSaleDetailRecyclerView.setVisibility(View.VISIBLE);
            mProcessTipLy.setVisibility(View.GONE);
            mGetSaleDetailFailTipLy.setVisibility(View.GONE);
            mSwipeRefreshLayout.setRefreshing(true);
        }

        @Override
        protected List<PayMaster> doInBackground(String... params) {
            if (SearchSaleDetailActivity.this.isFinishing()) {
                return null;
            }
            int r = 0;
            if (mHeaderOrFooter == true) {
                mReadIndex = 0;
            }
            r = mReadIndex;

            List<PayMaster> result = new ArrayList<PayMaster>();
            List<SaleDetailInfo> saleDetailList = new ArrayList<>();
            HashMap<String, Object> temp = new HashMap<String, Object>();
            if (BarApplication.getInstance().mDatabaseIsSqlServer)
                saleDetailList = DatabaseManager.getSaleDetailInfoFromSqlServer(SearchSaleDetailActivity.this, 0, mSearchStr);
            else
                saleDetailList = DatabaseManager.getSaleDetailInfoFromLocal(SearchSaleDetailActivity.this, 0, mSearchStr);

            for (SaleDetailInfo saleDetailInfo : saleDetailList) {
                if (!temp.containsKey(saleDetailInfo.saleDetailBillno)) {
                    PayMaster pay = new PayMaster();
                    pay.payMasterBillno = saleDetailInfo.saleDetailBillno;
                    pay.payMasterBlotout = 0;
                    pay.payMasterReceivable = saleDetailInfo.saleDetailQuantity * saleDetailInfo.saleDetailPrice;
                    pay.payMasterTotal = saleDetailInfo.saleDetailQuantity * saleDetailInfo.saleDetailPrice;
                    pay.payMasterOperdate = saleDetailInfo.saleDetailOperdate;
                    pay.payMasterOpertime = saleDetailInfo.saleDetailOpertime;
                    result.add(pay);
                    temp.put(saleDetailInfo.saleDetailBillno, pay);
                } else {
                    PayMaster pay = (PayMaster) temp.get(saleDetailInfo.saleDetailBillno);
                    pay.payMasterReceivable = pay.payMasterReceivable + saleDetailInfo.saleDetailQuantity * saleDetailInfo.saleDetailPrice;
                    pay.payMasterTotal = pay.payMasterTotal + saleDetailInfo.saleDetailQuantity * saleDetailInfo.saleDetailPrice;
                }
            }
            mReadIndex = mReadIndex + result.size();
            return result;
        }

        @Override
        protected void onPostExecute(final List<PayMaster> result) {
            super.onPostExecute(result);
            if (SearchSaleDetailActivity.this.isFinishing()) {
                return;
            }
            if (result != null) {
                switch (mSearchMode) {
                    case SEARCH_BY_SALEDETAIL_BILLNO:
                        //mSearchResultTv.setText(String.valueOf(mReadIndex));
                        break;
                    default:
                        break;
                }
                if (result != null && result.size() != 0) {
                    //mSearchResultTv.setVisibility(View.VISIBLE);
                } else {
                    //mSearchResultTv.setVisibility(View.GONE);
                }

                if (mHeaderOrFooter == true) {
                    Message _Msg = mHandler.obtainMessage(REFRESH_DATA_FINISH, result);
                    mHandler.sendMessage(_Msg);
                } else {
                    Message _Msg = mHandler.obtainMessage(LOAD_DATA_FINISH, result);
                    mHandler.sendMessage(_Msg);
                }
            }
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    private void showResultView() {
        if (mSaleDetailRecyclerViewAdapter.getItemCount() == 0) {
            mSaleDetailRecyclerView.setVisibility(View.GONE);
            mProcessTipLy.setVisibility(View.GONE);
            mGetSaleDetailFailTipLy.setVisibility(View.VISIBLE);
            mSaleDetailFailTipTv.setText("无搜索结果");
        } else {
            mSaleDetailRecyclerView.setVisibility(View.VISIBLE);
            mProcessTipLy.setVisibility(View.GONE);
            mGetSaleDetailFailTipLy.setVisibility(View.GONE);
        }
    }

    private void displayWithAnimator(final View v, final float alpha, final int time) {
        int sysVersion = Integer.parseInt(Build.VERSION.SDK);
        if (sysVersion >= 11) {
            final ValueAnimator animator = ValueAnimator.ofFloat(ViewHelper.getAlpha(v), alpha);
            animator.setDuration(time);
            animator.setInterpolator(new DecelerateInterpolator());//线性效果变化
            animator.start();
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    Float integer = (Float) valueAnimator.getAnimatedValue();
                    ViewHelper.setAlpha(v, integer);
                }
            });
        } else {
            AlphaAnimation alphaAnimation = new AlphaAnimation(ViewHelper.getAlpha(v), alpha);
            alphaAnimation.setDuration(time);
            v.startAnimation(alphaAnimation);
            alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    ViewHelper.setAlpha(v, alpha);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
        }
    }
}
